<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="JVM08, Max|Blog">
    <meta name="description" content="life is a fucking movie">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>JVM08 | Max|Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.3.0"><link rel="alternate" href="/atom.xml" title="Max|Blog" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Max|Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Max|Blog</div>
        <div class="logo-desc">
            
            life is a fucking movie
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/zhy2021/zhy2021.github.io" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/zhy2021/zhy2021.github.io" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/17.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">JVM08</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                          <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                          </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-10-20
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    4.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    14 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="垃圾回收"><a href="#垃圾回收" class="headerlink" title="垃圾回收"></a>垃圾回收</h1><h2 id="什么是垃圾"><a href="#什么是垃圾" class="headerlink" title="什么是垃圾"></a>什么是垃圾</h2><p><img src="https://s1.ax1x.com/2020/10/20/Bpo82t.png"></p>
<blockquote>
<p>垃圾收集的三个经典问题：</p>
<ul>
<li>哪些内存需要回收</li>
<li>什么时候回收</li>
<li>如何回收</li>
</ul>
</blockquote>
<h3 id="面试题"><a href="#面试题" class="headerlink" title="面试题"></a>面试题</h3><p><img src="https://s1.ax1x.com/2020/10/20/BpTay6.png"></p>
<p><img src="https://s1.ax1x.com/2020/10/20/BpTsFH.png"></p>
<blockquote>
<p>什么是垃圾？</p>
</blockquote>
<p><strong>运行程序中没有任何指针指向的对象</strong></p>
<blockquote>
<p>为何要gc</p>
</blockquote>
<p><img src="https://s1.ax1x.com/2020/10/20/Bp7oDK.png"></p>
<h2 id="垃圾回收相关算法"><a href="#垃圾回收相关算法" class="headerlink" title="垃圾回收相关算法"></a>垃圾回收相关算法</h2><h3 id="标记阶段：引用计数法"><a href="#标记阶段：引用计数法" class="headerlink" title="标记阶段：引用计数法"></a>标记阶段：引用计数法</h3><blockquote>
<p><strong>死亡对象：</strong>当一个对象不被任何存活的对象所引用时，<strong>就已经宣判了死亡</strong></p>
<p><strong>引用计数法：</strong>对每一个对象保存一个整型的引用计数器属性，用于存放对象被引用的情况</p>
</blockquote>
<p><strong>优点</strong>：</p>
<ul>
<li>实现简单，垃圾对象便于辨识；判定率高，回收没有延迟性</li>
</ul>
<p><strong>缺点</strong>：</p>
<ul>
<li>它需要单独的字段存储计数器，增加了空间的开销</li>
<li>每次赋值需要更新计数器，伴随着加减法的操作，增加了时间的开销</li>
<li>引用计数器不能处理 <strong>循环引用的情况</strong> （a引用了b，，b引用了a，但是二者都不会被使用，所以会造成<strong>内存泄漏</strong>）</li>
</ul>
<p><img src="https://s1.ax1x.com/2020/10/21/B9wxp9.png"></p>
<h3 id="标记阶段：可达性分析法"><a href="#标记阶段：可达性分析法" class="headerlink" title="标记阶段：可达性分析法"></a>标记阶段：可达性分析法</h3><blockquote>
<p>主要是用来解决在引用计数法中的循环引用的问题，防止内存泄漏的发生。</p>
</blockquote>
<p>基本思路：</p>
<ul>
<li>可达性分析算法是以根对象集合为起始点，按照从上到下的方式 <strong>搜索被根对象集合所连接的目标对象是否可达</strong>。</li>
<li>使用可达性分析算法后，内存中的存活对象都会被根对象集合直接或间接链接着，搜索所走过的路径称为 <strong>引用链</strong>。</li>
<li>如果目标对象没有任何引用链相连，则是不可达的，就意味着该对象已经死亡，可以标记为垃圾对象。</li>
<li>在可达性分析算法中，只有能够被根对象集合直接或者间接链接的对象才是存活对象。</li>
</ul>
<p><img src="https://s1.ax1x.com/2020/10/21/B96mcQ.png"></p>
<h4 id="面试：在java语言中，谁可以作为GC-Roots"><a href="#面试：在java语言中，谁可以作为GC-Roots" class="headerlink" title="面试：在java语言中，谁可以作为GC Roots??"></a>面试：在java语言中，谁可以作为GC Roots??</h4><blockquote>
<ul>
<li>虚拟机栈中引用的对象</li>
<li>本地方法栈JNI引用的对象</li>
<li>方法区类静态属性引用的对象</li>
<li>方法区中常量引用的对象</li>
<li>所有被同步锁synchronized持有的对象</li>
<li>java虚拟机内部的引用</li>
<li>反映java虚拟机内部情况的JMXBean、JVMTI中注册的回调、本地代码缓存等</li>
<li>除了这些固定的GC Roots集合以外，根据用户所选用的垃圾收集器以及当前回收的内存区域不同，还可以有其他对象“临时性”加入，共同构建出GC Roots集合。比如：<strong>分代收集和局部回收</strong></li>
</ul>
</blockquote>
<p><strong>小技巧：</strong></p>
<p>由于Root采用栈方式存放变量和指针，所以如果一个指针，它保存了堆内存里面的对象，但是自己又不在堆中，那么它就是一个root</p>
<h3 id="对象的finalization机制"><a href="#对象的finalization机制" class="headerlink" title="对象的finalization机制"></a>对象的finalization机制</h3><p><strong>finalize()方法的调用</strong></p>
<blockquote>
<p>当垃圾回收的时候，会调用垃圾的这个方法，他是父类Object的方法，我们可以重写它。<strong>用于资源释放，关闭文件，断开数据库链接，关闭套接字等等。。。。。。。。。。。。</strong></p>
</blockquote>
<p><img src="C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20201021105110443.png" alt="image-20201021105110443"></p>
<p><strong>三种可能的状态</strong>：</p>
<ul>
<li><strong>可触及的</strong>，从根节点可以访问到这个对象</li>
<li><strong>可复活的</strong>，对象的所有引用都被释放，但是对象可能在finalize()中复活</li>
<li><strong>不可触及的</strong>，对象的finalize()被调用了，并且没有复活，那么就会触及到不可触及的状态，因为<strong>finalize()只会触发以此</strong></li>
</ul>
<p><img src="C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20201021110219387.png" alt="image-20201021110219387"></p>
<h3 id="MAT与JProfiler的GC-root溯源"><a href="#MAT与JProfiler的GC-root溯源" class="headerlink" title="MAT与JProfiler的GC root溯源"></a>MAT与JProfiler的GC root溯源</h3><blockquote>
<p>略，dump文件和jprofiler的认识</p>
</blockquote>
<h3 id="清除阶段：标记清除算法"><a href="#清除阶段：标记清除算法" class="headerlink" title="清除阶段：标记清除算法"></a>清除阶段：标记清除算法</h3><blockquote>
<p>Mark-Sweep算法</p>
</blockquote>
<p><strong>执行过程</strong>：</p>
<p>当内存中的有效空间被耗尽的时候，就会停止整个程序STW，然后进行两项工作：标记，清除</p>
<ul>
<li><strong>标记</strong>：Collerctor从根节点开始遍历，<strong>标记所有被引用的对象</strong>！！！！！！，是非垃圾对象。一般是在对象的Header中记录可达对象。</li>
<li><strong>清除</strong>：Collector对堆内存从头到尾进行线性的遍历，如果发现某个对象在其Header中没有标记为可达对象，则将其回收。</li>
</ul>
<img src="https://img02.sogoucdn.com/app/a/100520146/43f91e8295dd41d570c4cc65d86cbc71" alt="UTOOLS1603263356735.png" title="UTOOLS1603263356735.png" />

<p><strong>缺点</strong>：</p>
<ul>
<li>效率不算高</li>
<li>在GC的时候，需要停止整个应用程序，导致用户体验差</li>
<li>这种方式清理出来的空闲内存是不连续的，会产生内存碎片，需要维护一个<strong>空闲列表</strong></li>
</ul>
<p><strong>注意：何为清除？</strong></p>
<ul>
<li>这里所谓的清除并不是置空，而是<strong>把需要消除的对象地址保存在空闲的地址列表中</strong>。下次有新对象需要加载时，判断垃圾的位置空间是否够，如果够，就存放。</li>
</ul>
<h3 id="清除阶段：复制算法"><a href="#清除阶段：复制算法" class="headerlink" title="清除阶段：复制算法"></a>清除阶段：复制算法</h3><blockquote>
<p>为了解决标记清除算法在垃圾收集效率方面的缺陷，所以出现</p>
</blockquote>
<p><strong>核心思想：</strong></p>
<p>将活着的内存空间分为两块，每次只是用其中一块，在垃圾回收时将正在使用的内存中的存活对象复制到为使用的内存快中，之后清除正在使用的内存块中的所有对象，交换两个内存的角色，完成垃圾回收。</p>
<p><img src="https://img04.sogoucdn.com/app/a/100520146/2a65b0db2928d712e3a9c0b2533ce53e" alt="UTOOLS1603264536577.png"></p>
<p><strong>优点：</strong></p>
<ul>
<li>没有标记和清除过程，实现简单，运行高效</li>
<li>复制过去以后保证空间的连续性，不会出现“碎片”问题</li>
</ul>
<p><strong>缺点</strong>：</p>
<ul>
<li>此算法使得我们需要两倍的内存空间</li>
<li>对于G1这种分拆成为大量region的GC，复制而不是移动，意味着GC需要维护region之间对象引用关系，不管是内存占用还是时间开销都不小</li>
</ul>
<p><strong>特别的：</strong></p>
<blockquote>
<p>如果系统中垃圾对象不是很多，复制算法需要复制的存活对象数量就会很大。</p>
<p>正是我们想到新生代里通常可以回收70%-99%的内存空间，回收性价比很高，所以新生代用此垃圾回收算法非常合适！！！！</p>
</blockquote>
<p><img src="C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20201021152950491.png" alt="image-20201021152950491"></p>
<h3 id="清除阶段：标记-压缩-Mark-Compact-算法"><a href="#清除阶段：标记-压缩-Mark-Compact-算法" class="headerlink" title="清除阶段：标记-压缩(Mark-Compact)算法"></a>清除阶段：标记-压缩(Mark-Compact)算法</h3><blockquote>
<p>复制算法的高效性是建立在 <strong>存活对象比较少，垃圾对象比较多的情况下</strong>。</p>
<p>基于<strong>老年代这种存活对象很多，垃圾很少的情况</strong>，我们应该使用其他的算法</p>
</blockquote>
<p><strong>执行过程：</strong></p>
<ul>
<li><p>第一阶段和标记-清除算法一样，从根节点开始<strong>标记所有被引用对象</strong></p>
</li>
<li><p>第二阶段<strong>将所有存活对象压缩到内存的一端</strong>，按顺序排放</p>
</li>
<li><p>之后<strong>清理边界外所有的空间</strong></p>
</li>
</ul>
<p><img src="https://img01.sogoucdn.com/app/a/100520146/652a44131a13048a2b40512e3574a3a2" alt="UTOOLS1603266197927.png"></p>
<p><strong>优点：</strong></p>
<ul>
<li>消除了标记-清除算法当中，内存区域分散的缺点，我们需要给新对象分配内存时，JVM只需要持有一个内存的起始地址即可。</li>
<li>消除了复制算法当中，内存减半的高额代价</li>
</ul>
<p><strong>缺点：</strong></p>
<ul>
<li>从效率上，比不过复制算法</li>
<li>移动对象的同时，如果对象被其他对象引用，则还需要调整引用的地址</li>
<li>移动过程中，需要全程暂停用户应用程序。STW</li>
</ul>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><blockquote>
<p>效率</p>
</blockquote>
<p>复制算法是当之无愧的老大，但是却浪费了太多的内存</p>
<blockquote>
<p>空间开销</p>
</blockquote>
<p>标记清除算法很快，复制算法需要额外的空间来维护存活对象的存放和空闲列表</p>
<blockquote>
<p>移动对象</p>
</blockquote>
<p>复制算法要比标记压缩算法快</p>
<h3 id="分代收集算法"><a href="#分代收集算法" class="headerlink" title="分代收集算法"></a>分代收集算法</h3><blockquote>
<p>基于：不同对象的生命周期是不一样的，<strong>因此不同生命周期的对象可以采取不同的收集方式，以便提高回收效率。</strong>一般把java堆分为新生代和老年代，这样就可以根据各个年代的特点使用不同的垃圾回收算法</p>
</blockquote>
<p><strong>几乎所有的GC都是采用分代收集算法执行垃圾回收的</strong></p>
<h3 id="增量收集算法"><a href="#增量收集算法" class="headerlink" title="增量收集算法"></a>增量收集算法</h3><blockquote>
<p>在之前的算法中，应用软件将处于STW的状态，如果垃圾回收时间过长，就会严重影响用户体验或者系统稳定性。</p>
</blockquote>
<p><strong>解决思路</strong>：</p>
<p>每次，垃圾收集线程<strong>只收集一小片区域的内存空间</strong>，接着切换到应用程序线程，依次反复，直到垃圾收集完成。</p>
<p>总的来说，增量收集算法的基础仍是传统的标记-清除和复制算法。增量收集算法通过 <strong>对线程间冲突的妥善处理，允许垃圾收集线程以分阶段的方式完成标记，清理或复制工作。</strong></p>
<p><strong>缺点</strong>：</p>
<p>使用这种方式，由于在垃圾回收过程中，间断性地还执行了应用程序代码，所以能减少系统的停顿时间。但是，因为线程切换和上下文转换的小号，会使得垃圾回收的总体成本上升，<strong>造成系统吞吐量的下降</strong></p>
<h3 id="分区算法"><a href="#分区算法" class="headerlink" title="分区算法"></a>分区算法</h3><blockquote>
<p>目的：为了更好的控制GC产生的停顿时间，将一块大的内存区域分割成多个小块，根据目标的停顿时间，每次合理地回收若干个小区间 region ，而不是整个堆空间，从而减少一次gc所产生的停顿。</p>
<p>每个小区间都独立使用，独立回收。</p>
</blockquote>
<p><img src="https://img01.sogoucdn.com/app/a/100520146/b93984920170e301aa380981ad69315c" alt="UTOOLS1603270969499.png"></p>
<h2 id="垃圾回收相关概念"><a href="#垃圾回收相关概念" class="headerlink" title="垃圾回收相关概念"></a>垃圾回收相关概念</h2><h3 id="System-gc的理解"><a href="#System-gc的理解" class="headerlink" title="System.gc的理解"></a>System.gc的理解</h3><blockquote>
<p>通过System.gc和Runtime.getRuntime().gc() 会显示的触发 <strong>full gc</strong></p>
</blockquote>
<p><strong>然而</strong>，System.gc()调用附带一个免责声明，无法保证对垃圾收集器的调用</p>
<p><img src="https://img04.sogoucdn.com/app/a/100520146/41269ef6fa92e05832fe313bb29cc247" alt="UTOOLS1603272636302.png"></p>
<p>程序结束了，但是gc还是没有发生，但是有时候可以。</p>
<p>我们可以调用 System.runFinalization(); 会强制调用使用引用的对象的finalize()方法</p>
<h3 id="内存溢出和内存泄漏"><a href="#内存溢出和内存泄漏" class="headerlink" title="内存溢出和内存泄漏"></a>内存溢出和内存泄漏</h3><blockquote>
<p>内存溢出</p>
</blockquote>
<ul>
<li>没有空闲内存，并且垃圾收集器也无法提供更多内存</li>
</ul>
<p>原因：</p>
<ul>
<li>java虚拟机的堆内存设置不够</li>
<li>代码中创建了大量大对象，并且长时间不能被垃圾收集器收集（有引用）</li>
</ul>
<blockquote>
<p>内存泄漏</p>
</blockquote>
<ul>
<li><p>严格意义上将，<strong>只有对象不会被程序用到了，并且GC又不能回收他们的情况</strong>，叫做内存泄漏。</p>
</li>
<li><p>但实际情况中，很多时候一些不太好的疏忽会<strong>导致对象的生命周期变得很长甚至导致OOM</strong>。也可以叫做<strong>宽泛意义</strong>上的“内存泄漏”</p>
</li>
</ul>
<p><img src="https://img03.sogoucdn.com/app/a/100520146/c7c5b0b31f6c15f07bb9b2668f2c6b7a" alt="UTOOLS1603284239687.png"></p>
<p>忘记断开了引用链，，让本该释放的对象，还被引用着，不能被释放</p>
<p><strong>举例：</strong></p>
<ol>
<li><p>单例模式</p>
<blockquote>
<p>单例模式的生命周期和应用程序是一样长的，所以<strong>单例程序</strong>中，如果<strong>持有对外部对象的引用的话，那么这个外部对象是不能回收的</strong>，则会导致内存泄漏的发生。</p>
</blockquote>
<p><img src="https://img01.sogoucdn.com/app/a/100520146/2897cee1accd74b0e563477bd51f2c43"></p>
</li>
<li><p>一些提供close的资源未关闭导致内存泄漏</p>
<blockquote>
<p>跟数据库，网络链接，io链接必须手动关闭，否则是不能被回收的！！！！！！！！！！</p>
</blockquote>
</li>
</ol>
<h3 id="STW"><a href="#STW" class="headerlink" title="STW"></a>STW</h3><blockquote>
<p>GC事件发生过程中，会产生程序的停顿，线程会被暂停，没有任何响应，这个停顿称为STW</p>
</blockquote>
<ul>
<li>可达性分析算法中枚举根节点会导致所有java执行的线程停顿<ul>
<li>分析工作必须在一个能确保一致性的快照中进行</li>
<li>一致性指整个分析期间整个执行系统看起来像被冻结在某个时间点上</li>
<li><strong>如果出现分析过程中对象引用关系还在不断变化，则分析过程的准确性无法保证</strong></li>
</ul>
</li>
<li>被STW中断的应用程序线程会在完成GC后恢复，频繁的STW会让用户体验感极差，所有要减少 </li>
</ul>
<h3 id="垃圾回收的并行与并发"><a href="#垃圾回收的并行与并发" class="headerlink" title="垃圾回收的并行与并发"></a>垃圾回收的并行与并发</h3><blockquote>
<p><strong>并发</strong>：不是真正意义上的“同时执行”，只是CPU把一个时间段划分成几个时间片段（时间区间），然后在这几个时间区间之间来回切换，由于CPU处理的速度非常快，只要时间间隔处理得当，即可让用户感觉是多个应用程序同时在进行。</p>
<p><strong>并行</strong>：当系统有一个以上CPU时，当一个CPU执行一个进程，另一个CPU可以执行另一个进程，两个进程互不抢占CPU资源，可以同时进行，我们称之为<strong>并行</strong></p>
<ul>
<li>决定并行的不是cpu数量，而是cpu核心数量，一个cpu多核也能并行</li>
<li>适合科学计算，后台处理等弱交互场景</li>
</ul>
</blockquote>
<p>并发：<strong>在一个时间段内同时发生了</strong></p>
<p><img src="https://img03.sogoucdn.com/app/a/100520146/6eaac6b00ac4b10c6c82730c3643d60e" alt="UTOOLS1603286445704.png"></p>
<p>并行：<strong>在一个时间点上同时发生了</strong></p>
<p><img src="https://img04.sogoucdn.com/app/a/100520146/bb13aee526a47dd0975ad3e895b3c8b5" alt="UTOOLS1603286412378.png"></p>
<h3 id="安全点与安全区域"><a href="#安全点与安全区域" class="headerlink" title="安全点与安全区域"></a>安全点与安全区域</h3><blockquote>
<p>程序执行时，并非是在所有地方都能停顿下来GC，只有在特定的位置才可，这些位置称为“安全点”（safe point）</p>
</blockquote>
<h4 id="如何在GC发生时，检查所有线程都跑到最近的安全点停顿下来？"><a href="#如何在GC发生时，检查所有线程都跑到最近的安全点停顿下来？" class="headerlink" title="如何在GC发生时，检查所有线程都跑到最近的安全点停顿下来？"></a>如何在GC发生时，检查所有线程都跑到最近的安全点停顿下来？</h4><ul>
<li><p><strong>抢先式中断</strong>：（目前没有虚拟机使用了）</p>
<blockquote>
<p>首先中断所有线程，如果还有线程不在安全点，就恢复线程，让线程跑到安全点</p>
</blockquote>
</li>
<li><p><strong>主动式中断</strong>：</p>
<blockquote>
<p>设置一个中断标志，各个线程运行到Safe Point的时候主动轮询这个标志，如果中断标志为真，则将自己进行中断挂起</p>
</blockquote>
</li>
</ul>
<p><strong>安全区域</strong></p>
<blockquote>
<p>安全区域是指在一段代码片段中，对象的引用关系不会发生变化，在这个区域中的任何位置开始GC都是安全的 Safe Region</p>
</blockquote>
<h3 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h3><blockquote>
<p>我们希望能描述这样一类对象：当内存空间还很足时，则能保存在内存中；如果内存空间在进行垃圾收集后还是很紧张，则可以抛弃这些对象</p>
</blockquote>
<h4 id="【即偏门又高频的面试题】"><a href="#【即偏门又高频的面试题】" class="headerlink" title="【即偏门又高频的面试题】"></a>【即偏门又高频的面试题】</h4><blockquote>
<p>强引用，软引用，弱引用，虚引用有什么区别？具体使用场景是什么？</p>
</blockquote>
<p><strong>强度对比：</strong>强引用-&gt;软引用-&gt;弱引用-&gt;虚引用</p>
<p><img src="https://img04.sogoucdn.com/app/a/100520146/3a999af1a2e69f4a387d0ba1e6e5d951" alt="UTOOLS1603288830450.png"></p>
<h4 id="强引用（死也不回收）"><a href="#强引用（死也不回收）" class="headerlink" title="强引用（死也不回收）"></a>强引用（死也不回收）</h4><blockquote>
<p><strong>最传统的引用定义</strong>，是指在程序代码之中普遍存在的引用赋值，<strong>无论任何情况下都不会回收</strong> </p>
</blockquote>
<ul>
<li>强引用对象时可触及的，<strong>GC永远不会回收掉被引用的对象</strong></li>
<li><strong>强引用时造成java内存泄漏的主要原因之一</strong></li>
</ul>
<h4 id="软引用-内存不够才回收"><a href="#软引用-内存不够才回收" class="headerlink" title="软引用(内存不够才回收)"></a>软引用(内存不够才回收)</h4><blockquote>
<p>在系统没有发生内存不足前，一切正常。<strong>当系统内存溢出之前，会把这些对象列入回收范围中进行二次回收</strong>。如果这次回收还没有足够的内存，才会抛出内存溢出异常</p>
</blockquote>
<ul>
<li>软引用通常用来实现内存敏感的缓存，比如 <strong>高速缓存</strong>就有用到软引用，如果又空闲的内存就会保留，加快执行效率，如果内存不足，就清理掉</li>
<li><code>SoftReference</code>来实现软引用 </li>
<li>但是，如果在伊甸园区不够了，老年代还是够呢，就会把软引用放在老年代中</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">SoftReference</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">></span></span> softRef <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SoftReference</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">User</span><span class="token punctuation">(</span>xxx<span class="token punctuation">)</span><span class="token punctuation">)</span>   用此来构建软引用
    
    softRef<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  可以获得软引用中的对象<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="弱引用"><a href="#弱引用" class="headerlink" title="弱引用"></a>弱引用</h4><blockquote>
<p><strong>只被弱引用关联</strong>的对象只能生存在下一次垃圾回收之前，，<strong>GC工作的时候，不管你内存够不够，都会把弱引用回收</strong>，但是垃圾回收器的线程通常优先级很低，所以不一定很快地发现持有弱引用的对象。在这种情况下，<strong>弱引用对象可以存在较长的时间</strong>。</p>
</blockquote>
<ul>
<li>构造弱引用时，指定一个引用队列，当弱引用对象被回收时，就会加入指定的引用队列，通过这个队列可以追踪对象的回收情况</li>
<li>跟软引用一样，适合保存那些可有可无的缓存数据</li>
<li><code>WeakReference&lt;T&gt;</code>可以创建软引用</li>
</ul>
<h5 id="面试题：开发中用过WeakHashMap吗？？？？？？？"><a href="#面试题：开发中用过WeakHashMap吗？？？？？？？" class="headerlink" title="面试题：开发中用过WeakHashMap吗？？？？？？？"></a>面试题：开发中用过WeakHashMap吗？？？？？？？</h5><blockquote>
<p>内部类entity继承了weakReference，实现了弱引用</p>
</blockquote>
<p><img src="https://img03.sogoucdn.com/app/a/100520146/e235696434669c44185a411d02ce78e6" alt="UTOOLS1603373350703.png"></p>
<h4 id="虚引用（对象跟踪-）"><a href="#虚引用（对象跟踪-）" class="headerlink" title="虚引用（对象跟踪 ）"></a>虚引用（对象跟踪 ）</h4><blockquote>
<p><strong>唯一目的时能够在这个对象回收之前收到一个系统的通知</strong>，用于对象回收跟踪</p>
</blockquote>
<ul>
<li>为一个对象设置虚引用关联的唯一目的在于 <strong>跟踪垃圾回收过程</strong>。比如：能在这个对象被收集器回收时收到一个系统通知</li>
<li><strong>虚引用必须跟引用队列一起使用</strong>。虚引用在创建时必须提供一个引用队列作为参数。当垃圾回收器准备回收一个对象时，如果发现它有虚引用，就会在回收对象后，将这个虚引用加入引用队列，以通知应用程序对象的回收情况</li>
<li><strong>由于虚引用可以跟踪对象的回收时间</strong>，因此，<strong>可以将一些资源释放操作放置在虚引用中执行和记录</strong></li>
<li>PhantomReference 实现虚引用</li>
<li>虚引用不能通过 xxx.get()方法获取到！！！！！！</li>
</ul>
<h4 id="终结器引用"><a href="#终结器引用" class="headerlink" title="终结器引用"></a>终结器引用</h4><blockquote>
<p><strong>用来实现对象的finalize()方法</strong>，也称为终结器引用。</p>
</blockquote>
<ul>
<li>无需手动编码，其内部配合引用队列使用</li>
<li>gc时，把终结器放入引用队列，用Finalizer线程通过终结器引用找到被引用对象，并调用它的finalize()方法，第二次GC的时候才会回收被引用的对象</li>
</ul>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Max</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhy2021.github.io/2020/10/20/jvm08/">https://zhy2021.github.io/2020/10/20/jvm08/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Max</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: '5FkhQebEqGdoNnuL654mv5KM-gzGzoHsz',
        appKey: 'NNEBzCiygD4tBLqHt8diLxda',
        notify: 'true' === 'true',
        verify: 'true' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2020/10/22/jvm09/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/18.jpg" class="responsive-img" alt="JVM09">
                        
                        <span class="card-title">JVM09</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            垃圾回收器的相关信息
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-10-22
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/jvm/" class="post-category">
                                    jvm
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/jvm/">
                        <span class="chip bg-color">jvm</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/10/18/jvm07/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/16.jpg" class="responsive-img" alt="JVM07">
                        
                        <span class="card-title">JVM07</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            string table 的相关问题
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-10-18
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/jvm/" class="post-category">
                                    jvm
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/jvm/">
                        <span class="chip bg-color">jvm</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: Max|Blog<br />'
            + '文章作者: Max<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=default"></script>

    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="2844914148"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">Max</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">141.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "2";
                    var startDate = "13";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1181062873@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1181062873" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1181062873" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
